package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.model.dto.PageQueryDTO;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }
    @Autowired
    private MapApi mapApi;

    /**
     * 新增地址
     *
     * @param dto
     */
    @Override
    public void add(AddressBookUpsertReqDTO dto) {
        if (dto==null){
            throw new BadRequestException("参数异常");
        }
        AddressBook addressBook = BeanUtil.toBean(dto, AddressBook.class);
        addressBook.setUserId(UserContext.currentUserId());
        LocationResDTO location = mapApi.getLocationByAddress(dto.getAddress());
        String[] loca = location.getLocation().split(",");
        addressBook.setLon(Double.valueOf(loca[0]));
        addressBook.setLat(Double.valueOf(loca[1]));
        //如果为默认地址,其他地址状态改变
        this.lambdaUpdate().eq(AddressBook::getUserId,UserContext.currentUserId())
                .set(AddressBook::getIsDefault,0).update();
         this.save(addressBook);

    }

    @Autowired
    private AddressBookMapper addressBookMapper;
    /**
     * 分页查询地址
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<AddressBook> addressPage(PageQueryDTO dto) {
        Long userId = UserContext.currentUserId();
        PageHelper.startPage(dto.getPageNo().intValue(), dto.getPageSize().intValue());
        Page<AddressBook> addressBooks = (Page<AddressBook>) addressBookMapper.addressPage(userId,dto);
        PageResult<AddressBook> pageResult = new PageResult<>();
        pageResult.setTotal(addressBooks.getTotal());
        pageResult.setPages(Long.valueOf(addressBooks.getPages()));
        pageResult.setList(addressBooks.getResult());
        return pageResult;
    }

    /**
     * 地址铺详情
     *
     * @param id
     * @return
     */
    @Override
    public AddressBook address(Long id) {
        if (id==null){
            throw new BadRequestException("请求id为空");
        }
        AddressBook addressBook = this.getById(id);
        if (addressBook==null){
            throw new BadRequestException("id无地址");
        }
        return addressBook;
    }

    /**
     * 地址铺修改
     *
     * @param id
     * @param dto
     */
    @Override
    public void updateaddress(Long id, AddressBookUpsertReqDTO dto) {
        AddressBook addressBook = BeanUtil.toBean(dto, AddressBook.class);
        if (id==null){
            throw new BadRequestException("参数id异常");
        }
        addressBook.setId(id);
        boolean result = this.updateById(addressBook);
        if (!result){
            throw  new RuntimeException("修改失败");
        }
    }

    /**
     * 地址铺删除
     *
     * @param ids
     */
    @Override
    public void delteaddress(List<Long> ids) {
        if (CollUtils.isEmpty(ids)){
            throw new BadRequestException("参数为空");
        }
        for (Long id : ids) {
            boolean update = this.lambdaUpdate().eq(AddressBook::getId, id).set(AddressBook::getIsDeleted, 1).update();
            if (!update){
                throw new RuntimeException("地址铺删除失败");
            }
        }

    }

    /**
     * 设置/取消默认地址
     *
     * @param flag
     * @param id
     */
    @Override
    public void defaultAddressbook(Integer flag, Long id) {
        if (flag==null||id==null){
            throw new BadRequestException("参数异常");
        }
        if (flag==1){
            boolean userup =this.lambdaUpdate().eq(AddressBook::getUserId,UserContext.currentUserId()).set(AddressBook::getIsDefault,0).update();
            if (!userup){
                throw new RuntimeException("其他地址未修改成功");
            }
        }
        boolean result = this.lambdaUpdate().eq(AddressBook::getId, id).set(AddressBook::getIsDefault, flag).update();
        if (!result){
            throw new RuntimeException("设置/取消默认地址失败");
        }
    }

    /**
     * 获取默认地址
     */
    @Override
    public AddressBook defaultAddress() {
        AddressBook addressBook = this.lambdaQuery().eq(AddressBook::getUserId,UserContext.currentUserId()).eq(AddressBook::getIsDefault, 1).eq(AddressBook::getIsDeleted, 0).one();
        return addressBook;
    }
}
